<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <searchrevealing>
        <el-tabs v-model="activeTab">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
            <el-form-item label="商品编码/69码" prop="styleCode">
              <el-input v-model="queryParams.styleCode" placeholder="请输入" clearable maxlength="20" style="width: 220px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类目" prop="categoryIds">
              <el-cascader v-model="queryParams.categoryIds" :options="options" style="width: 220px" filterable
                clearable ref="categoryRef" @change="handleChange" placeholder="请选择" :props="props" />
            </el-form-item>
            <el-form-item label="商品名称" prop="styleName">
              <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable maxlength="50"
                style="width: 220px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合作方式" prop="cooperationMode">
              <el-select style="width: 220px" v-model="queryParams.cooperationMode" placeholder="请选择合作方式" filterable
                clearable>
                <el-option v-for="dict in hm_cooperation_mode" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                :remote-method="searchQuery" class="supplierSelect" style="width: 220px" :loading="supplierQueryLoading"
                @clear="handleClear">
                <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
                <template v-if="supplierLoading">
                  <div class="supplierSelect_icon">
                    <el-icon class="el-select-loading__icon">
                      <Loading />
                    </el-icon>
                    <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                  </div>
                </template>
                <template #loading>
                  <svg class="circular" viewBox="0 0 50 50">
                    <circle class="path" cx="25" cy="25" r="20" fill="none" />
                  </svg>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="部门类型" prop="types">
              <el-select v-model="queryParams.types" placeholder="请选择部门类型" clearable filterable
                @change="(e: string) => { departmentTypeChange('type', e) }" style="width: 220px">
                <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                  :value="dict.deptId" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门名称" prop="recruiterDeptId">
              <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门名称" clearable filterable
                @change="deptChange" style="width: 220px">
                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName" :value="dict.deptId" />
              </el-select>
            </el-form-item>
            <el-form-item label="人员名称" prop="recruiterUserId">
              <el-select v-model="queryParams.recruiterUserId" placeholder="请选择人员名称" clearable filterable
                style="width: 220px">
                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                  :value="dict.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="选品部门" prop="coreId">
              <el-select v-model="queryParams.coreId" placeholder="请选择" clearable filterable style="width: 220px">
                <el-option v-for="dict in anchorList" :key="dict.deptId" :label="dict.deptName"
                  :value="dict.deptId"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="初次送审" prop="requestSecondNum">
              <el-select v-model="queryParams.requestSecondNum" placeholder="请选择是否初次送审" clearable filterable
                style="width: 220px">
                <el-option v-for="dict in debutList" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

          </el-form>
          <div class="form_button">
            <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
            <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
          </div>
        </el-tabs>
      </searchrevealing>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'核价部核价复审待复核'"
          @updateColumn="getColmun"></right-toolbar>
      </template>
      <el-table v-loading="loading" :data="supplierAddProductsList" @selection-change="handleSelectionChange" border
        row-key="productsId" @header-dragend="dragEnd">
        <el-table-column v-for="(item, index) in pendingValuationColumns" :key="index" :label="item.label"
          align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
          <template #default="scope">
            <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50" :height="50" />

            <div v-if="item.prop == 'hmMechanismsList'">
              <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                null,
                '一') }}</div>
              <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                null,
                '二') }}</div>
              <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                null,
                '三') }}</div>
            </div>
            <!-- 主播 -->
            <div v-if="item.prop == 'coreName'">
              <div class="flex">
                <img v-if="scope.row.changeType == 1 || scope.row.changeType == 3" class="downloadpic"
                  :src="shuangjiantou" />
                <div :class="(scope.row.changeType == 1 || scope.row.changeType == 3) ? 'coreName' : 'coreNames'">
                  {{ scope.row.coreName }}</div>
              </div>
            </div>
            <!-- 招商部 -->
            <span v-if="item.prop == 'recruiterDept'">{{ scope.row.auditFirstLog?.requestDeptName }}</span>
            <!-- 招商员 -->
            <span v-if="item.prop == 'recruiter'">{{ scope.row.auditFirstLog?.requestNickName }}</span>
            <!-- 初审通过时间 -->
            <span v-if="item.prop == 'auditTime'">{{ scope.row.auditFirstLog?.auditTime }}</span>
            <!-- 初审人 -->
            <span v-if="item.prop == 'auditNickName'">{{ scope.row.auditFirstLog?.auditNickName }}</span>
            <!-- 是否初次复核 -->
            <span v-if="item.prop == 'requestSecondNum'">{{ scope.row.requestSecondNum == '1' ? '是' : '否'
              }}</span>
            <!-- 最近送审时间 -->
            <span v-if="item.prop == 'requestTime'">{{ scope.row.auditSecondFirstLog?.requestTime }}</span>
            <!-- 最近复核时间 -->
            <span v-if="item.prop == 'auditTimes'">{{ scope.row.auditSecondLog?.auditTime }}</span>
            <!-- 驳回建议 -->
            <span v-if="item.prop == 'auditRemark'">{{ scope.row.auditSecondLog?.auditRemark }}</span>
            <span v-if="item.prop == 'type'">{{ scope.row.type == 1 ? '研发部' : '招商部' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleGoodWarehousing(scope.row)" class="color_theme"
              style="margin-left: 0px !important">去复核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
    </el-card>
    <!-- 核价 -->
    <commoditymodify @doClose="commoditymodifyClose" :commoditydetailsData="commoditymodifyData"
      :dialogInfoVisible="commoditymodifyVisible"></commoditymodify>
  </div>
</template>
<script setup name="pendingValuation" lang="ts">
const { proxy } = getCurrentInstance() as any;
import commoditymodify from './commoditymodify.vue';
import { getPageByTaskSecond, getSecondDetailsById } from '@/api/group/productSelectionPricing';
import { QualityControlQuery, ContractTable } from '@/api/group/productSelectionPricing/types';
import { getUserList, getSystemList } from '@/api/group/qualityControl';
import { loginSupplierList } from '@/api/group/supplier/index';
import { getCategoryLists } from '@/api/group/productOutbound';
import { queryOperationDeptList } from '@/api/group/productSelectionPricing';
import shuangjiantou from '@/assets/images/shuangjiantou.png';
const anchorList = ref<{ deptName: string; deptId: string }[]>([]);
const pendingValuationColumns = ref();
const props = {
  checkStrictly: true
};

const { hm_cooperation_mode } = toRefs<any>(proxy?.useDict('hm_cooperation_mode'));
const columnData = ref();

const activeTab = ref('qualityControl');
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const supplierAddProductsList = ref<ContractTable[]>([]);
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([]);
// 部门类型
const departmentTypeList = ref<{ deptId: string; deptName: string }[]>([]);
const deptList = ref<{ deptId: string; deptName: string }[]>([]);
const recruiterList = ref<{ userId: string; nickName: string }[]>([]);
const categoryRef = ref();
const options = ref();
const supplierNameOptions = ref<any[]>([]);
const supplierNameDate = ref({
  pageNum: 1,
  pageSize: 10,
  supplierName: ''
});
const supplierQueryLoading = ref(false);
const supplierLoading = ref(true);
const supplierNametotal = ref();
const queryLoading = ref(false);

const commoditymodifyVisible = ref(false);
const commoditymodifyData = ref<ContractTable>();

// 初次送审
const debutList = ref([
  { label: '是', value: '1' },
  { label: '否', value: '0' }
]);

const data = reactive<PageData<{}, QualityControlQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    styleCode: undefined,
    categoryId: undefined,
    categoryIds: undefined,
    styleName: undefined,
    cooperationMode: undefined,
    recruiterDeptId: undefined,
    recruiterUserId: undefined,
    supplierId: undefined,
    requestSecondNum: undefined,
    coreId: undefined,
    types: undefined
  },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);
// 获取供应商列表
const getHmSupplierList = async () => {
  supplierLoading.value = true;
  const res = await loginSupplierList(supplierNameDate.value);
  const reshandle = res.rows.map((item: any) => ({
    label: item.supplierName,
    value: item.id
  }));
  supplierNameOptions.value.push(...reshandle);
  supplierNametotal.value = res.total;
  supplierLoading.value = false;
};
/**
 * 直播机制
 */
const computedMechanism = (row: any, numbers: string) => {
  if (row) {
    const price = row.price ? row.price : '-';
    const commission = row.commission ? row.commission + '%' : '-';
    const brokerage = row.brokerage ? row.brokerage + '%' : '-';
    const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-';
    const costPrice = row.costPrice ? row.costPrice : '-';
    if (row.cooperationMode) {
      if (row.cooperationMode == '分佣') {
        return (
          '机制' +
          numbers +
          ': ' +
          '售价:' +
          price +
          ' 佣金:' +
          commission +
          ' 补充佣金:' +
          brokerage +
          ' 机制:' +
          liveStreamingMechanism +
          ' 成本:' +
          costPrice
        );
      } else {
        return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism;
      }
    }
  }
};
// 获取选品部门
const getAnchor = async () => {
  const res = await queryOperationDeptList()
  anchorList.value = res.data
};
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
  if (val) {
    categoryRef.value.togglePopperVisible();
    queryParams.value.categoryIds = val[val.length - 1];
    queryParams.value.categoryId = val.join(',');
  }
};
/**
 * 部门筛选
 */
const departmentTypeChange = async (type: string, id: string) => {
  deptList.value = [];
  recruiterList.value = [];
  queryParams.value.recruiterDeptId = undefined;
  queryParams.value.recruiterUserId = undefined;
  if (id) {
    const res = await getSystemList({ parentId: id });
    if (type === 'init') {
      departmentTypeList.value = res.data;
    } else {
      deptList.value = res.data;
    }
  }
};
/** 获取类目 */
const getCategoryList = async () => {
  try {
    const res = await getCategoryLists();
    const processedData = renameField(res.data);
    options.value = processedData;
  } catch (error) {
    console.error('Failed to get category list:', error);
    options.value = [];
  }
};
const renameField = (arr: any[]) => {
  return arr
    .filter((item) => item.categoryStatus === 0)
    .map((element) => {
      if (element.children) {
        element.children = renameField(element.children);
      }
      return {
        label: element.categoryName,
        value: element.categoryId,
        ...element
      };
    });
};

/** select懒加载 */
const selectLoad = async () => {
  if (supplierNameOptions.value.length < supplierNametotal.value) {
    supplierNameDate.value.pageNum++;
    getHmSupplierList();
  }
};
/** 远程搜索 */
const searchQuery = async (query: string) => {
  supplierQueryLoading.value = true;
  supplierNameOptions.value = [];
  supplierNameDate.value.pageNum = 1;
  supplierNameDate.value.pageSize = 10;
  supplierNameDate.value.supplierName = query;
  await getHmSupplierList();
  supplierQueryLoading.value = false;
};
/** 清空供应商 */
const handleClear = () => {
  supplierNameDate.value.supplierName = '';
  supplierNameOptions.value = [];
  supplierNameDate.value.pageNum = 1;
  supplierNameDate.value.pageSize = 10;
  getHmSupplierList();
};

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
  queryParams.value.recruiterUserId = undefined;
  if (event) {
    const res = await getUserList({ deptId: event });
    recruiterList.value = res.rows;
  } else {
    recruiterList.value = [];
  }
};

/** 查询列表 */
const getList = async () => {
  try {
    loading.value = true;
    let params = {
      ...queryParams.value,
      recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
    };
    const res = await getPageByTaskSecond(params);
    supplierAddProductsList.value = res.rows;
    total.value = res.total;
    loading.value = false;
    queryLoading.value = false;
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

/** 页数变化 */
const paginationChange = async () => {
  await getList();
  await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize);
  getColmun()
};

/** 搜索按钮操作 */
const handleQuery = () => {
  if (!queryParams.value.categoryIds) {
    queryParams.value.categoryId = undefined;
  }
  queryLoading.value = true;
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.categoryId = undefined;
  recruiterList.value = [];
  deptList.value = [];
  handleClear();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: ContractTable[]) => {
  ids.value = selection.map((item) => item.id);
};

/** 去核价 */
const handleGoodWarehousing = async (row: ContractTable) => {
  const res: any = await getSecondDetailsById({
    id: row.id
  });
  res.data.bigVideos = import.meta.env.VITE_APP_PIC_URL + res.data.bigVideo;
  commoditymodifyData.value = res.data;
  commoditymodifyVisible.value = true;
};
// 去核价关闭
const commoditymodifyClose = () => {
  commoditymodifyVisible.value = false;
  getList();
};

/** 获取colmun */
const getColmun = async () => {
  const columnDatas = await proxy?.useColumn('核价部核价复审待复核');
  pendingValuationColumns.value = columnDatas.columnCustom;
  columnData.value = columnDatas;
  queryParams.value.pageSize = columnDatas.columnPageSize || 10;
};
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
  columnData.value.columnCustom.map((item: any) => {
    if (item.prop == column.property) {
      item.width = newWidth;
    }
  });
  await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize);
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.downloadAsync(
    'basic/hmProducts/getSecondAuditExport',
    {
      ...queryParams.value,
      recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
    },
    `核价复审待复审_${new Date().getTime()}.xlsx`
  );
};

onMounted(async () => {
  queryParams.value.pageNum = 1;
  departmentTypeChange('init', '1861962988832542721');
  await getColmun();
  await getList();
  getAnchor();
  getCategoryList();
});
</script>
<style lang="scss" scoped>
.two-line {
  overflow: hidden;
  display: -webkit-box;
  /* 将对象作为弹性伸缩盒子模型显示 */
  -webkit-line-clamp: 2;
  /* 行数，值可以改，表示展示X行后多余的缩略展示 */
  -webkit-box-orient: vertical;
  /* 设置或检索伸缩盒对象的子元素的排列方式 */
  word-break: break-all;
}

.mb96 {
  margin-bottom: 96px;
}

.form_button {
  display: flex;
  justify-content: flex-end;
}

.circular {
  display: inline;
  height: 30px;
  width: 30px;
  animation: loading-rotate 2s linear infinite;
}

.path {
  animation: loading-dash 1.5s ease-in-out infinite;
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: var(--el-color-primary);
  stroke-linecap: round;
}

.supplierSelect {
  :deep(.el-popper) {
    left: 0 !important;
    top: 34px !important;
    z-index: 7000 !important;
    width: 100% !important;
  }
}

:deep(.el-tabs__content) {
  overflow: visible !important;
}

.supplierSelect_icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.el-select-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: initial;
  pointer-events: none;
  color: var(--el-color-info);
  font-size: 12px;

  &__icon {
    font-size: 16px;
    animation: rotate 1.5s linear infinite;
  }

  &__tips {
    margin-left: 6px;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
}

.el-select-loading__tips {
  color: #606266;
  font-size: 14px;
}

:deep(.el-card__header) {
  display: flex;
  justify-content: flex-end;
}

.flex {
  display: flex;
  align-items: center;
  line-height: 1;
  width: 100%;

  .downloadpic {
    width: 15px;
    height: 15px;
  }

  .coreName {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: calc(100% - 15px);
  }

  .coreNames {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
  }
}
</style>